package dk.com.dao;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.impl.cookie.DateParseException;

import dk.com.entities.BaseEntities;
import dk.com.entities.H2ConnectionBuilder;
import dk.com.entities.SQLHelper;
import dk.com.util.ClassUtils;
import dk.com.util.DateUtils;

public class BaseDao<T extends BaseEntities> {
	private Class <T> clazz;
	private List<Field> listFields;
	public BaseDao(Class<T> theClass) {
		this.clazz = theClass;
		listFields = ClassUtils.getAllFields(theClass);
	}

	public List<T> getAll() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, DateParseException{
		List<T> result = new ArrayList<T>();
		H2ConnectionBuilder h2Builder = new H2ConnectionBuilder();
		SQLHelper<T> sqlHelper = new SQLHelper<T>(clazz);
		ResultSet rs = h2Builder.getStat().executeQuery(sqlHelper.makeSQLGetAll());
		
		T record = clazz.newInstance();
		while (rs.next()) {
			record = fetchDetail(rs);
			result.add(record);
		}
		return result;
	}

	private T fetchDetail(ResultSet rs) throws IllegalArgumentException, IllegalAccessException, SQLException, InstantiationException {
		T record = clazz.newInstance();
		for(Field field : listFields){
			field.setAccessible(true);
			Class<?> fileType = field.getType();
			if(fileType.toString().equalsIgnoreCase(Date.class.toString())){
				field.set(record,DateUtils.convertFromString(rs.getString(field.getName())));
			}
			if(fileType.toString().equalsIgnoreCase(Integer.class.toString())){
				field.set(record,Integer.parseInt(rs.getString(field.getName())));
			}
			
			if(fileType.toString().equalsIgnoreCase(String.class.toString())){
				field.set(record,rs.getString(field.getName()) );
			}
			
		}
		return record;
	}
	
	
}
